package com.kischang.blog.web.actionuser;

import com.kischang.blog.model.User;
import com.kischang.blog.service.UserService;
import com.kischang.blog.utils.Utils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.kischang.blog.utils.Utils.isNull;

@Component
@Scope("prototype")
public class RegisterAction extends ActionSupport {

    private static boolean NOTREG = true;

	private static final long serialVersionUID = 6952953119606173712L;
	@Resource
	private UserService userService;
	private String username;
	private String password;
	private String password2;
	private String email;
	private String code;

	private String msg;
	private int stat;

    private List<User> users;

	@Override
	public String execute() throws Exception {
        if(NOTREG){
            msg = "禁用服务！！！";
            stat = 7;
            return SUCCESS;
        }
		stat = 0;
		if(isNull(code) || !checkCode(code)){
			msg = "验证码错误！！！";
			stat = 6;
			return SUCCESS;
		}
		// 验证码已经使用了，使其失效
		UserRegisterCodeImg.failureCode();
		
		if (isNull(username) || isNull(password) || isNull(password2) || isNull(email)) {
			msg = "用户名、密码、邮箱不能为空！！！";
			stat = 1;
			return SUCCESS;
		}
		if (!password.equals(password2)) {
			msg = "两次输入的密码不一致！！！";
			stat = 2;
			return SUCCESS;
		}
		if(userService.checkUsernameIsExists(username)){
			msg = "用户名已存在！！！";
			stat = 3;
			return SUCCESS;
		}
		if(!checkUsername(username)){
			msg = "用户名格式错误！！！";
			stat = 3;
			return SUCCESS;
		}
		if(!checkPassword(password)){
			msg = "密码格式错误！！！";
			stat = 4;
			return SUCCESS;
		}
		if(!checkEmail(email)){
			msg = "邮箱格式错误！！！";
			stat = 5;
			return SUCCESS;
		}
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		user.setNickname(username);
		user.setHead("/image/def_head.jpg");
		user.setRole(2);
		user.setEmail(email);
		//发送验证邮件
		String activeCode = Utils.getActivecode(24);
		user.setActivecode(activeCode);
		//保存用户
		userService.saveUser(user);
		
		String activeUrl = "http://localhost:8080/Blog/user/update_active?code="+activeCode.substring(0, activeCode.indexOf("|"));
		String textContent = "您好：\r\n"
				+ "   谢谢您注册我的博客，用户名是："+username+"，\r\n请您在24小时之内点击连接\r\n"+activeUrl+" 激活您的邮箱，\r\n"
				+ "如果您没有注册，请忽略本邮件。\r\n邮件激活后您能享受本博客网站的全部服务！请您务必遵守互联网规定，文明上网！！！";
		System.err.println("sendEmail>>"+Utils.sendMail(email, "don't reply-用户邮箱激活", textContent));
		msg = "恭喜您注册成功，请在24小时之内验证您的邮箱！！！";
		msg += textContent;
		return SUCCESS;
	}
	
	public String view(){
        if(NOTREG){
            users = userService.getAll();
            return "NOTREG";
        }
		return "view";
	}
	
	private boolean checkCode(String code2) {
		String str = (String) ActionContext.getContext().getSession().get(UserRegisterCodeImg.REG_CODE);
		if(code2.toLowerCase().equals(str.toLowerCase()))
			return true;
		return false;
	}

	//26个英文字母加数字的组合 >6
	public boolean checkUsername(String un) {
		if(un.length()<=6)
			return false;
		Pattern pattern = Pattern.compile("^[A-Za-z0-9]+$");
		Matcher matcher = pattern.matcher(un);
		return matcher.matches();
	}
	//26个英文字母加数字和符号的组合 >6
	public boolean checkPassword(String ps) {
		if(ps.length()<=6)
			return false;
		Pattern pattern = Pattern.compile("^[A-Za-z0-9\\S]+$");
		Matcher matcher = pattern.matcher(ps);
		return matcher.matches();
	}
	
	public boolean checkEmail(String email) {
		Pattern pattern = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
		Matcher matcher = pattern.matcher(email);
		return matcher.matches();
	}

	public String getMsg() {
		return msg;
	}
	public int getStat() {
		return stat;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public void setPassword2(String password2) {
		this.password2 = password2;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public void setCode(String code) {
		this.code = code;
	}

    public List<User> getUsers() {
        return users;
    }

    public static void setNOTREG(boolean b) {
        NOTREG = b;
    }

    public static boolean getNOTREG() {
        return NOTREG;
    }
}